package cn.stylefeng.guns.modular.order.controller;

import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;

import cn.stylefeng.guns.core.util.justApi;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.order.entity.OrderPutExcelItem;
import cn.stylefeng.guns.modular.order.entity.WhOutOrder;
import cn.stylefeng.guns.modular.order.model.params.WhOutOrderParam;
import cn.stylefeng.guns.modular.order.service.WhOutOrderService;
import cn.stylefeng.guns.modular.tool.model.params.ToolOrderPutParam;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 武汉出库订单表控制器
 *
 * @author wp
 * @Date 2025-09-30 11:13:38
 */
@Controller
@RequestMapping("/whOutOrder")
public class WhOutOrderController extends BaseController {

    private String PREFIX = "/order/whOutOrder";

    @Autowired
    private WhOutOrderService whOutOrderService;

    @Autowired
    private UserService userService;
    @Autowired
    private BasicCustomerService basicCustomerService;
    @Autowired
    private BasicWarehouseService basicWarehouseService;

    /**
     * 跳转到主页面
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "/whOutOrder.html";
    }

    /**
     * 新增页面
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("/add")
    public String add() {
        return PREFIX + "/whOutOrder_add.html";
    }

    /**
     * 编辑页面
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/whOutOrder_edit.html";
    }

    /**
     * 新增接口
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(WhOutOrderParam whOutOrderParam) {
        this.whOutOrderService.add(whOutOrderParam);
        return ResponseData.success();
    }

    /**
     * 编辑接口
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(WhOutOrderParam whOutOrderParam) {
        this.whOutOrderService.update(whOutOrderParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(WhOutOrderParam whOutOrderParam) {
        this.whOutOrderService.delete(whOutOrderParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(WhOutOrderParam whOutOrderParam) {
        WhOutOrder detail = this.whOutOrderService.getById(whOutOrderParam.getId());
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author wp
     * @Date 2025-09-30
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(WhOutOrderParam whOutOrderParam,String condition ) {
        return this.whOutOrderService.findPageBySpec(whOutOrderParam,condition);
    }
    /**
     * 跳转到JST出库页面
     *
     * @author wp
     * @Date 2025-09-30
     */
    @RequestMapping("/toJSTOutOrder")
    public String toJSTOutOrder( Model model){
//		Long deliverId = userService.getDeliverId();
//		model.addAttribute("deliverId",deliverId);
//		model.addAttribute("outCustomerId",outCustomerId);
        User user = userService.getcurrentUser();
        Long deptId = user.getDeptId();
        Long deliverId = user.getDeliverId();
        //查询可选择仓库
        model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        //查询可选择客户
        model.addAttribute("customerlist", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

        return PREFIX + "/toJSTOutOrder.html";
    }

    /**
     * 获取JST出库订单【武汉】
     * @param toolOrderPutParam
     * @param modified_begin
     * @param modified_end
     * @return
     */
    @ResponseBody
    @RequestMapping("/getJSTOutOrder")
    public ResponseData getJSTOutOrder(ToolOrderPutParam toolOrderPutParam, String modified_begin, String modified_end){

        User user = userService.getcurrentUser();
        BasicCustomer byId = basicCustomerService.getById(147);
        String justAppsecret = byId.getJustAppsecret();
        String justAppkey = byId.getJustAppkey();
        String accessToken = byId.getAccessToken();

//		ApiResponse jstDdcx = JstDdcx.getJstDdcx(justAppkey, justAppsecret, accessToken,
//				null,modified_begin,modified_end);
//		System.out.println("jstDdcx:" + jstDdcx.toString());
//
//		ResponseData responseData = outOrderService.saveJstOutOrder(jstDdcx, user, byId);
        ResponseData responseData = new ResponseData();

        List<OrderPutExcelItem> list = new ArrayList<OrderPutExcelItem>();
        Integer page_index = 1;//页数
        boolean has_next = true;//是否有下一页
        while (has_next) {
            //只能分页查询，一页最多50条
            //接口调用频率秒级内不超过5次，分钟内不超过100次
            String data = null;
//			ApiResponse jstDdcx = null;
            try {
                data = justApi.getWhSellerItem(justAppkey,justAppsecret,accessToken, modified_begin, modified_end,null ,page_index.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
//			ObjectMapper mapper = new ObjectMapper();
//			try {
//				jstDdcx = mapper.readValue(data, ApiResponse.class);
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
            org.json.JSONObject jsonObject = new org.json.JSONObject(data);
            if(jsonObject.get("code").toString().equals("0")) {
                String data1 = jsonObject.get("data").toString();
                JSONObject jsonObject1 = new JSONObject(data1);
                if(Integer.parseInt(jsonObject1.get("data_count").toString()) > 0) {
                    if(jsonObject1.get("has_next").toString().equals("false")) {
                        has_next = false;
                    }
//                    responseData = outOrderService.saveJstOutOrder(jsonObject1, user, byId);
                    responseData = whOutOrderService.saveJstOutOrder(jsonObject1, user, byId);

                } else {
                    has_next = false;
                    responseData.setSuccess(false);
                    responseData.setMessage("未获取到快递明细");
                }
            } else {
                has_next = false;
                responseData.setSuccess(false);
                responseData.setMessage("拉取失败！"+data);
            }

            page_index++;
            if(has_next) {
                try {
                    Thread.currentThread().sleep(650);//如果有下一页 等待0.65秒
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        return responseData;
    }

}


